package com.jnu.student.myfirstapplication.ui.task;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.student.myfirstapplication.R;
import com.jnu.student.myfirstapplication.data.TaskItem;
import com.jnu.student.myfirstapplication.ui.DataSave;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OneTaskFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OneTaskFragment extends Fragment {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

    private String data1;
    private String data2;

    private ArrayList<TaskItem> mTasksList = new ArrayList<>();
    private ArrayList<TaskItem> mFinishedTasksList = new ArrayList<>();
    ActivityResultLauncher<Intent> addTaskLauncher;
    ActivityResultLauncher<Intent> refactorTaskLauncher;
    private TaskAdapter adapter_local;
    boolean finished = false;

    public OneTaskFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param dataname1 Parameter 1.
     * @param dataname2 Parameter 2.
     * @return A new instance of fragment OneTaskFragment.
     */
    public static OneTaskFragment newInstance(String dataname1, String dataname2) {
        OneTaskFragment fragment = new OneTaskFragment();
        Bundle args = new Bundle();
        args.putString("data1", dataname1);
        args.putString("data2", dataname2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            data1 = getArguments().getString("data1");
            data2 = getArguments().getString("data2");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
//        View root = inflater.inflate(R.layout.fragment_one_task, container, false);
//        TextView textView = root.findViewById(R.id.textTest);
//        textView.setText(data1 + ' ' + data2);
//        return root;
        View root = inflater.inflate(R.layout.fragment_award, container, false);
        TextView nullTipTextView = root.findViewById(R.id.nullTipText);
        FloatingActionButton floatingActionButton = root.findViewById(R.id.addButton);
        floatingActionButton.setVisibility(View.VISIBLE);
        mTasksList = new DataSave(data1).LoadItems(requireActivity());
        mFinishedTasksList = new DataSave(data2).LoadItems(requireActivity());
        // 添加的数据处理
//        mAwardsList.add(new TaskItem("award1", 20));
//        mAwardsList.add(new TaskItem("award2", 25));
//        mAwardsList.add(new TaskItem("award3", 30));
        RecyclerView recyclerView = root.findViewById(R.id.recycle_award);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireActivity());  //线性的布局管理器
        recyclerView.setLayoutManager(layoutManager);           //为recycleView绑定布局管理器

        TaskAdapter adapter = new TaskAdapter(mTasksList, false);      //数据管理的适配器
        TaskAdapter awardAdapterFinished = new TaskAdapter(mFinishedTasksList, true);
        registerForContextMenu(recyclerView);                   //注册上下文菜单
        recyclerView.setAdapter(adapter);                       //绑定适配器
        adapter_local = adapter;
        if (adapter_local.mlist.isEmpty() == true) {
            nullTipTextView.setText("数据为空，请添加任务");
            nullTipTextView.setVisibility(View.VISIBLE);
        } else {
            nullTipTextView.setVisibility(View.GONE);
        }

        floatingActionButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // 切换到添加奖励的activity并传递数据
                Toast.makeText(requireActivity(), "添加任务", Toast.LENGTH_SHORT).show();
                Intent intentAdd = new Intent(requireActivity(), AddTaskActivity.class);   // 从当前activity里创建有关参数二那个类的activity
                addTaskLauncher.launch(intentAdd);     // 执行新activity并处理返回结果
            }
        });


        Switch changeFinished = root.findViewById(R.id.finishedAwards);
        changeFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!b)
                {
                    compoundButton.setText("当前在奖励列表中");
                    recyclerView.setAdapter(adapter);                       //绑定适配器
                    adapter_local = adapter;
                    finished = true;
                    if (adapter_local.mlist.isEmpty() == true) {
                        nullTipTextView.setText("任务列表为空，请添加任务");
                        nullTipTextView.setVisibility(View.VISIBLE);
                    } else {
                        nullTipTextView.setVisibility(View.GONE);
                    }
                } else{
                    compoundButton.setText("当前在已完成任务的列表中");
                    recyclerView.setAdapter(awardAdapterFinished);                       //绑定适配器
                    adapter_local = awardAdapterFinished;
                    finished = false;
                    if (adapter_local.mlist.isEmpty() == true) {
                        nullTipTextView.setText("没有已完成的任务，请在任务列表界面完成任务");
                        nullTipTextView.setVisibility(View.VISIBLE);
                    } else {
                        nullTipTextView.setVisibility(View.GONE);
                    }
                }
            }
        });

        addTaskLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        String name = data.getStringExtra("name"); // 获取返回的数据
                        int score = data.getIntExtra("score", -1);

                        mTasksList.add(new TaskItem(name, score));   // 添加数据
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                        new DataSave(data1).SaveItems(requireActivity(), mTasksList);
                        adapter.notifyItemInserted(mTasksList.size());  // 适配器重新适配一下新出现的item

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        refactorTaskLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        int position = data.getIntExtra("position",0);
                        String name = data.getStringExtra("name"); // 获取返回的数据
                        int score = data.getIntExtra("score", -1); // 获取返回的数据

                        mTasksList.get(position).Rename(name);   // 修改数据
                        mTasksList.get(position).Rescore(score);

//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                        new DataSave(data1).SaveItems(requireActivity(), mTasksList);
                        adapter.notifyItemChanged(position);  // 适配器重新适配一下新改变的item

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        return root;
    }
    public class TaskAdapter extends RecyclerView.Adapter<OneTaskFragment.TaskAdapter.ViewHolder> {
        private ArrayList<TaskItem> mlist;
        private final boolean IsFinished;

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
            private final TextView title;
            private final TextView score;

            public ViewHolder(View view) {
                super(view);
                title = (TextView) view.findViewById(R.id.award_title);
                score = (TextView) view.findViewById(R.id.award_score);
                view.setLongClickable(true);                    // 长按响应
                view.setOnCreateContextMenuListener(this);      // 创建上下文菜单
                view.setLongClickable(true);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (IsFinished == false) {
                            Toast.makeText(requireActivity(), "任务增加点数中", Toast.LENGTH_SHORT).show();
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                            int score = Integer.parseInt(((TextView) v.findViewById(R.id.award_score)).getText().toString().substring(1));
                            builder.setTitle("任务将会增加点数" + score);
                            builder.setMessage("确定完成任务吗？");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int position = getAdapterPosition();
                                    mFinishedTasksList.add(mTasksList.get(position));
                                    mTasksList.remove(position);
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                                    new DataSave(data1).SaveItems(requireActivity(), mTasksList);
                                    new DataSave(data2).SaveItems(requireActivity(), mFinishedTasksList);
                                    adapter_local.notifyItemRemoved(position);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.create().show();
                        }
                        else {
                            Toast.makeText(requireActivity(), "撤销已完成的任务中", Toast.LENGTH_SHORT).show();
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                            int score = Integer.parseInt(((TextView) v.findViewById(R.id.award_score)).getText().toString().substring(1));
                            builder.setTitle("撤销已完成的任务，将会扣回点数" + score);
                            builder.setMessage("确定撤销完成吗？");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int position = getAdapterPosition();
                                    mTasksList.add(mFinishedTasksList.get(position));
                                    mFinishedTasksList.remove(position);
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                                    new DataSave(data1).SaveItems(requireActivity(), mTasksList);
                                    new DataSave(data2).SaveItems(requireActivity(), mFinishedTasksList);
                                    adapter_local.notifyItemRemoved(position);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.create().show();
                        }
                    }
                });
            }
            public TextView getTitle() {
                return title;
            }

            public TextView getScore() {
                return score;
            }

            // 上下文菜单的样子设定
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                if (IsFinished == false) {
                    menu.setHeaderTitle("具体操作");
                    menu.add(0, 0, this.getAdapterPosition(), "删除");
                    menu.add(0, 1, this.getAdapterPosition(), "修改");
                }
            }
        }

        public TaskAdapter(ArrayList<TaskItem> mlist, boolean IsFinished) {
            this.mlist = mlist;
            this.IsFinished = IsFinished;
        }
        @NonNull
        @Override
        public OneTaskFragment.TaskAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.award_detail, parent, false);
            return new OneTaskFragment.TaskAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull OneTaskFragment.TaskAdapter.ViewHolder holder, int position) {
            TaskItem awardItem = mlist.get(position);
            holder.getTitle().setText(awardItem.getTaskName());
            TextView score = holder.getScore();
            score.setTextColor(getResources().getColor(R.color.green));
            score.setText("+"+awardItem.getTaskScore());
        }

        @Override
        public int getItemCount() {
            return mlist.size();
        }
        // 实现必要的方法
    }
    public boolean onContextItemSelected(MenuItem item) {
        // 处理菜单项的点击事件
        switch (item.getItemId()) {
            case 0:
                // 菜单项1的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("删除任务"+ item.getOrder());
                builder.setMessage("确定删除这一任务吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTasksList.remove(item.getOrder());
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                        new DataSave(data1).SaveItems(requireActivity(), mTasksList);
                        adapter_local.notifyItemRemoved(item.getOrder());
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();
                break;
            case 1:
                // 菜单项2的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                Intent intentRename = new Intent(requireActivity(), AddTaskActivity.class);
                TaskItem ItemRefactor= mTasksList.get(item.getOrder());
                intentRename.putExtra("name",ItemRefactor.getTaskName());
                intentRename.putExtra("score",ItemRefactor.getTaskScore());
                intentRename.putExtra("position",item.getOrder());
                refactorTaskLauncher.launch(intentRename);
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }
}